<template>
  <section>
    <!--工具条：关键字查询 + 新增-->
    <el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
      <el-form :inline="true">
        <el-form-item>
          <el-input v-model="keyword" placeholder="请输入关键字"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" v-on:click="keywordQuery">关键字查询</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="primary"  @click="handleAdd">新增</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="success"  @click="onsale">上架</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="warning"  @click="offsale">下架</el-button>
        </el-form-item>
      </el-form>
    </el-col>

    <!--列表:优秀实践，copy domain修改列表-->
    <el-table :data="pets" highlight-current-row v-loading="listLoading"
              @selection-change="selsChange" style="width: 100%;">
      <el-table-column type="selection" width="55">
      </el-table-column>
      <el-table-column type="index" width="60">
      </el-table-column>
      <el-table-column prop="name" label="宠物名称" width="100" sortable>
      </el-table-column>
      <el-table-column prop="costprice" label="成本" width="100" sortable>
      </el-table-column>
      <el-table-column prop="saleprice" label="售价" width="100" sortable>
      </el-table-column>
      <el-table-column prop="petType.name" label="宠物类型" width="100" sortable>
      </el-table-column>
      <!--<el-table-column prop="offsaletime" label="停售时间" width="120" sortable>
      </el-table-column>
      <el-table-column prop="onsaletime" label="出售时间" width="120" sortable>
      </el-table-column>-->
      <el-table-column prop="createtime" label="创建时间" width="120" sortable>
      </el-table-column>
      <el-table-column prop="shop.name" label="所属店铺" width="100" sortable>
      </el-table-column>
      <el-table-column prop="user.username" label="领养人" width="100" sortable>
      </el-table-column>
      <el-table-column prop="state" label="状态">
        <template slot-scope="props">
          <span v-if="props.row.state">
								<span style="color:#00B46D">上架</span>
          </span>
          <span v-else>
								<span style="color:#D75C89">下架</span>
          </span>
        </template>
      </el-table-column>
      <el-table-column prop="searchMasterMsgId" label="宠物来源" width="120">
        <template scope="scope">
          <span v-if="scope.row.searchMasterMsgId" style="color: green">来自寻主消息</span>
          <span v-else style="color: red">来自店铺饲养</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" >
        <template scope="scope">
          <el-button size="small" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
          <!-- v-perm="'pet:delete'" -->
          <el-button type="danger" size="small" @click="handleDel(scope.$index, scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!--工具条-->
    <el-col :span="24" class="toolbar">
      <el-button type="danger" @click="batchRemove" :disabled="this.sels.length===0">批量删除</el-button>
      <el-pagination layout="prev, pager, next" @current-change="handleCurrentChange"
                     :current-page="currentPage" :page-size="pageSize" :total="totals" style="float:right;">
      </el-pagination>
    </el-col>

    <!--新增和编辑对话框-->
    <el-dialog :title="title"  :visible.sync="saveFormVisible" :close-on-click-modal="false">
      <!--ref="saveForm" 指定表单名称，以后可以通过this.$refs.petForm-->
      <el-form :model="saveForm" label-width="80px" :rules="saveFormRules" ref="saveForm">
        <el-form-item label="名称" prop="name">
          <el-input v-model="saveForm.name" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="成本" prop="sn">
          <el-input v-model="saveForm.costprice" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="售价" prop="sn">
          <el-input v-model="saveForm.saleprice" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="宠物类型">
          <!--          <el-input v-model="saveForm.parent_id"></el-input>-->
          <el-cascader v-model="saveForm.typeId"
                       :options="petTree"
                       :props="{  checkStrictly: true ,label:'name',value:'id'}"
                       clearable></el-cascader>
        </el-form-item>
        <el-form-item label="状态">
          <el-radio-group v-model="saveForm.state">
            <el-radio class="radio" :label="1">上架</el-radio>
            <el-radio class="radio" :label="0">下架</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="所属店铺">
          <!--<el-input v-model="saveForm.manager_id" ></el-input>-->
          <el-select v-model="saveForm.shopId" placeholder="请选择" clearable>
            <el-option
                v-for="item in shops"
                :label="item.name"
                :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="资源" prop="resources">
          <el-upload class="upload-demo"
                     action="http://localhost:8080/fastDfs"
                     :on-remove="handleRemove"
                     :on-success="handleSuccess"
                     :file-list="fileList"
                     list-type="picture">
            <el-button size="small" type="primary">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
          </el-upload>
        </el-form-item>
        <el-form-item label="简介" prop="intro">
          <!-- v-if="saveForm.petDetail" 修改v-model绑定对象报错问题，v-if对需要显示的数据判断下 -->
          <quill-editor  v-model="saveForm.petDetail.intro" v-if="saveForm.petDetail" :options="quillOption">
          </quill-editor>
        </el-form-item>
        <el-form-item label="领养须知" prop="orderNotice" >
          <quill-editor  v-model="saveForm.petDetail.adoptNotice" v-if="saveForm.petDetail" :options="quillOption">
          </quill-editor>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click.native="saveFormVisible = false">取消</el-button>
        <el-button type="primary" @click.native="saveSubmit" :loading="saveLoading">保存</el-button>
      </div>
    </el-dialog>
  </section>
</template>

<script>

import { quillEditor } from "vue-quill-editor"; //调用编辑器
import 'quill/dist/quill.core.css';
import 'quill/dist/quill.snow.css';
import 'quill/dist/quill.bubble.css';
import quillConfig from '../../common/js/quill-config';

export default {
  components: {
    quillEditor
  },
  data() {
    return {
      //分页显示所属数据
      pets: [],
      listLoading: false,
      currentPage: 1,
      pageSize: 5,
      totals: 0,

      //高级查询所需数据
      keyword: null,

      //多条数据选中
      sels: [],//列表选中列

      //添加或修改数据
      saveFormVisible: false,//添加或修改界面是否显示
      saveLoading: false,
      title: null,
      saveFormRules: {
        name: [
          { required: true, message: '请输入宠物名称', trigger: 'blur' }
        ],
      },
      //编辑界面数据
      saveForm: {
        id:null,
        name:'',
        costprice:0,
        saleprice:0,
        typeId:null,
        resources:'',
        state:0,
        shopId:null,
        petDetail:{  //与后端实体类一致
          intro: '',
          adoptNotice: ''
        }
      },
      shops:[],
      petTree: [],
      quillOption: quillConfig,
      fileList : [],
    }
  },
  methods: {
    //获取员工列表
    getpets() {
      let paras = {
        currentPage: this.currentPage,
        pageSize: this.pageSize,
        keyword: this.keyword
      };
      this.listLoading = true;
      this.$http.post("/pet",paras).then(res => {
        this.totals = res.data.totals;
        this.pets = res.data.data;
        this.listLoading = false;
      }).catch(res => {
        this.$message.error("获取分页数据失败!!!");
      })
    },

    //关键字查询
    keywordQuery(){
      this.currentPage = 1;
      this.getpets();
    },

    //分页查询 - 点击某一页查询
    handleCurrentChange(val) {
      this.currentPage = val;
      this.getpets();
    },

    //删除
    handleDel: function (index, row) {
      this.$confirm('确认删除该记录吗?', '提示', {
        type: 'warning'
      }).then(() => {
        this.listLoading = true;
        this.$http.delete("/pet/" + row.id).then(res => {
          this.listLoading = false;
          if(res.data.success){
            //计算总页数
            let totalPage = this.totals%this.pageSize==0?this.totals/this.pageSize
                :Math.ceil(this.totals/this.pageSize);
            if(this.currentPage > 1 && this.currentPage==totalPage && (this.totals-1)%this.pageSize==0){
              this.currentPage = this.currentPage - 1;
            }
            this.getpets();
          }else{
            this.$message.error("删除失败【500】");
          }
        }).catch(res => {
          this.$message.error("系统错误【400,404】");
        })
      }).catch(() => {
        //确认框点击取消之后走这里
      });
    },

    //点击修改按钮弹出模态框
    handleEdit: function (index, row) {
      //回显数据：避免以前的数据发生改变
      this.saveForm = Object.assign({}, row);
      this.title = "修改";
      //加载所有店铺 - 方便选择宠物的所属店铺
      this.getShops();
      this.getPetTree();

      //处理fileList - 点击修改能够回显图片
      this.fileList = []; //先清空 - 这个fileList做了绑定，以前是有值【先清空，再添加最新的数据】
      if(this.saveForm.resources){
        // /group1/M00/00/0C/CgAIC2KrUU-ARA8EAAH2I5Y672k716.jpg,/group1/M00/00/0C/CgAIC2KrUYaAaR-6AADnxcxs4eA746.jpg
        var arr = this.saveForm.resources.split(",");
        for(var i = 0;i<arr.length;i++){
          var item = arr[i]; ///group1/M00/00/0C/CgAIC2KrUU-ARA8EAAH2I5Y672k716.jpg
          this.fileList.push({"url":"http://123.207.27.208" + item});
        }
      }
      //显示详情：两种方案：1.直接在分页查询时就把详情一并查询出来  2.点击编辑按钮弹出模态框的时候单独查询

      //显示对话框
      this.saveFormVisible = true;
    },

    //点击添加按钮弹出对话框
    handleAdd: function () {
      //修改对话框标题
      this.title = "添加";
      //置空数据
      this.saveForm =  {
        id:null,
        name:'',
        costprice:0,
        saleprice:0,
        typeId:null,
        resources:'',
        state:0,
        shopId:null,
        userId:null,
        petDetail:{  //与后端实体类一致
          intro: '',
          adoptNotice: ''
        },

      };
      this.getPetTree();//加载菜单树
      //加载所属店铺
      this.getShops();
      //清空fileList的数据
      this.fileList = [];
      //显示对话框
      this.saveFormVisible = true;
    },

    //点击对话框提交数据
    saveSubmit: function () {
      this.$refs.saveForm.validate((valid) => {
        if (valid) {
          this.$confirm('确认保存吗？', '提示', {}).then(() => {
            this.saveLoading = true;
            let para = Object.assign({}, this.saveForm);
            let arr = para.typeId;
            if(arr && arr.length==0){
              para.typeId = null;
            }else if(arr && arr.length>0){
              para.typeId = arr[arr.length-1];
            }
            this.$http.put("/pet",para).then((res) => {
              this.saveFormVisible = false;
              this.saveLoading = false;
              if(res.data.success){
                this.$message({
                  message: '提交成功',
                  type: 'success'
                });
                this.$refs['saveForm'].resetFields();//重置表单
                this.getpets(); //重新加载
              }else{
                this.$message.error("操作失败【500】");
              }
            }).catch(res => {
              this.$message.error("系统错误【400,404】");
            })
          });
        }
      });
    },

    selsChange: function (sels) {
      this.sels = sels;
    },

    //批量删除
    batchRemove: function () {
      //遍历选择记录把id放到一个数组中
      var ids = this.sels.map(item => item.id); //[1,2,3]
      this.$confirm('确认删除选中记录吗？', '温馨提示', {
        type: 'warning'
      }).then(() => {
        this.listLoading = true;
        this.$http.patch("/pet",ids).then((res) => {
          this.listLoading = false;
          if(res.data.success){
            this.$message.success("操作成功");
            this.currentPage = 1;
            this.getpets();
          }else{
            this.$message.error("批量删除失败【500】");
          }
        }).catch(res => {
          this.$message.error("系统错误【400,404】");
        })
      }).catch(() => {
      });
    },

    getShops(){
      this.$http.get("/shop").then(res=>{
        this.shops = res.data;
      })
    },

    getPetTree(){
      this.$http.get("/petType/petTypeTree").then(res => {
          this.petTree = res.data;
      });
    },

    handleSuccess(response, file, fileList){
      //对resources的处理 - 添加到数据库
      if(this.saveForm.resources){//有值返回true
        this.saveForm.resources = this.saveForm.resources + "," + response.resultObj;
      }else{
        this.saveForm.resources = response.resultObj;
      }

      //对fileList的处理 - 前端显示图片的
      this.fileList = []; //先清空 - 这个fileList做了绑定，以前是有值【先清空，再添加最新的数据】
      if(this.saveForm.resources){
        // /group1/M00/00/0C/CgAIC2KrUU-ARA8EAAH2I5Y672k716.jpg,/group1/M00/00/0C/CgAIC2KrUYaAaR-6AADnxcxs4eA746.jpg
        var arr = this.saveForm.resources.split(",");
        for(var i = 0;i<arr.length;i++){
          var item = arr[i]; ///group1/M00/00/0C/CgAIC2KrUU-ARA8EAAH2I5Y672k716.jpg
          this.fileList.push({"url":"http://123.207.27.208" + item});
        }
      }
    },

    handleRemove(file, fileList){
      //调用删除接口删除图片
      var path = file.url.substring(file.url.indexOf("/group")); //  /group1/M00/00/E5/CgAIC2Lc_7qAPinhAAEau2OL7dM844.jpg
      this.$http.delete("/fastDfs?path="+path).then(res=>{
        if(res.data.success){
          this.$message.success("删除成功")
        }else{
          this.$message.success("删除失败")
        }
      })

      //对resource做处理
      if(this.saveForm.resources){
        var arr = this.saveForm.resources.split(",");
        for(var i = 0;i<arr.length;i++){
          var item = arr[i];
          if(path==item){//找到了删除的图片
            arr.splice(i,1);//删除指定的图片
          }
        }
        this.saveForm.resources = arr.join(",")
      }
      //对fileList的处理
      this.fileList = []; //先清空
      if(this.saveForm.resources){
        var arr = this.saveForm.resources.split(",");
        for(var i = 0;i<arr.length;i++){
          var item = arr[i];
          this.fileList.push({"url":"http://123.207.27.208" + item});
        }
      }
    },

    onsale(){
      if(this.sels.length==0){
        this.$message.warning("没有选择上架的宠物");
        return ;
      }
      var ids = this.sels.map(item => item.id); //[1,2,3]
      this.$confirm('确认上架选中记录吗？', '温馨提示', {
        type: 'warning'
      }).then(() => {
        this.$http.post("/pet/onsale",ids).then((res) => {
          if(res.data.success){
            this.$message.success("上架成功");
            this.getpets();
          }else{
            this.$message.error(res.data.msg);
          }
        }).catch(res => {
          this.$message.error("上架失败【400，404】");
        })
      }).catch(() => {
      });

    },

    offsale(){
      if(this.sels.length==0){
        this.$message.warning("没有选择下架的宠物");
        return ;
      }
      var ids = this.sels.map(item => item.id); //[1,2,3]
      this.$confirm('确认下架选中记录吗？', '温馨提示', {
        type: 'warning'
      }).then(() => {
        this.$http.post("/pet/offsale",ids).then((res) => {
          if(res.data.success){
            this.$message.success("下架成功");
            this.getpets();
          }else{
            this.$message.error("下架失败【500】");
          }
        }).catch(res => {
          this.$message.error(res.data.msg);
        })
      }).catch(() => {
      });

    }

    },
  mounted() {
    this.getpets();
  }
}

</script>

<style scoped>

</style>